package com.ethink.framework.feign;

import cn.hutool.core.util.URLUtil;
import com.ethink.framework.common.constant.CommonConstant;
import com.ethink.framework.common.web.context.RequestContext;
import com.ethink.framework.common.web.context.SPRequestContextHolder;
import com.ethink.framework.log.constant.LogConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;

import java.util.Map;

/**
 * 调用下游服务的请求封装处理
 *
 * @author allen
 */
public class FeignRequestInterceptor implements RequestInterceptor {
    /**
     * 设置header传递，将当前服务的header信息传递到下游服务
     *
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        RequestContext requestContext = SPRequestContextHolder.getRequestContext();
        if (requestContext != null) {
            template.header(LogConstant.TRACE_ID_HEADER, requestContext.getTraceId());
            if (requestContext.getRequestEntityType() != null) {
                template.header(CommonConstant.RequestHeader.REQUEST_ENTITY_TYPE, requestContext.getRequestEntityType().name());
            }
            for (Map.Entry<String, String> entry : requestContext.getBizParamMap().entrySet()) {
                template.header(entry.getKey(), URLUtil.encode(entry.getValue()));
            }
        }
    }
}
